/*
 * Creative Commons Deed
 * Attribution-NonCommercial-ShareAlike 1.0 Finland
 * 
 * You are free:
 * 
 * * to copy, distribute, display, and perform the work
 * * to make derivative works
 * Under the following conditions:
 * 
 * Attribution. You must attribute the work in the manner specified by the author or licensor.
 * 
 * Noncommercial. You may not use this work for commercial purposes.
 * 
 * Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only 
 * under a license identical to this one.
 * 
 * * For any reuse or distribution, you must make clear to others the license terms of this work.
 * * Any of these conditions can be waived if you get permission from the copyright holder.
 * Your fair use and other rights are in no way affected by the above.
 * This is a human-readable summary of the Legal Code (the full license). 
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Net;

namespace PocketApps
{
    public class NucleusFileClass
    {

        public class NucleusFile
        {
            public enum FileType
            {
                Generic,
                Folder,
                Image, 
                Music, 
                Video,
                Package,
            }

            public string Width = "";
            
            public string Height = "";

            public FileType Type = FileType.Generic;

            public string Name = "";

            public override string ToString()
            {
                return Name;
            }
        }

        public string User = "";
        public string Pass = "";
        public string BaseUrl = "";
        public string ParentFolder = "";

        XmlDocument sndDoc = new XmlDocument();
        XmlDocument rcvDoc = new XmlDocument();

        void SendReceiveXml()
        {
            try
            {
                rcvDoc = new XmlDocument();
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(BaseUrl);

                req.Method = "POST";
                req.UserAgent = "TaskuBlogi 1.0";
                req.ContentType = "text/xml";

                byte[] data = Encoding.ASCII.GetBytes(sndDoc.InnerXml);
                req.ContentLength = data.Length;
                Stream newstream = req.GetRequestStream();
                newstream.Write(data, 0, data.Length);
                newstream.Close();
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                Stream restream = res.GetResponseStream();

                StringBuilder sbb = new StringBuilder();

                using (StreamReader sr = new StreamReader(restream))
                {
                    while (sr.Peek() != -1)
                    {
                        sbb.Append(sr.ReadToEnd());
                    }
                }
                restream.Close();

                rcvDoc.LoadXml(sbb.ToString());
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (XmlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch { }
        }
        
        public NucleusFile[] GetMediaList()
        {
            sndDoc = new XmlDocument();
            sndDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><fsRequest></fsRequest>");

            XmlNode root = sndDoc.DocumentElement;

            XmlNode authentication = sndDoc.CreateElement("authentication");
            root.AppendChild(authentication);

            XmlNode username = sndDoc.CreateElement("username");
            XmlText username_value = sndDoc.CreateTextNode(User);

            authentication.AppendChild(username);
            username.AppendChild(username_value);

            XmlNode password = sndDoc.CreateElement("password");
            XmlText password_value = sndDoc.CreateTextNode(Pass);

            authentication.AppendChild(password);
            password.AppendChild(password_value);

            XmlNode action = sndDoc.CreateElement("action");
            XmlText action_value = sndDoc.CreateTextNode("filelist");

            root.AppendChild(action);
            action.AppendChild(action_value);

            XmlNode parent = sndDoc.CreateElement("parent");
            XmlText parent_value = sndDoc.CreateTextNode(ParentFolder);

            root.AppendChild(parent);
            parent.AppendChild(parent_value);

            this.SendReceiveXml();

            XmlNode rcvStatus = rcvDoc.SelectSingleNode("descendant::status");

            if (rcvStatus!=null && rcvStatus.InnerText == "ok")
            {
                XmlNodeList files = rcvDoc.GetElementsByTagName("file");
                NucleusFile[] retFiles = new NucleusFile[files.Count];
                for (int i = 0; i < files.Count; i++)
                {
                    retFiles[i] = new NucleusFile();

                    retFiles[i].Name = files[i].Attributes["name"].Value;

                    if (files[i].Attributes["type"].Value == "folder")
                    {
                        retFiles[i].Type = NucleusFile.FileType.Folder;
                    }
                    else if (files[i].Attributes["type"].Value == "image")
                    {
                        retFiles[i].Type = NucleusFile.FileType.Image;
                        retFiles[i].Width = files[i].Attributes["width"].Value;
                        retFiles[i].Height = files[i].Attributes["height"].Value;
                    }
                    else if (files[i].Attributes["type"].Value == "music")
                    {
                        retFiles[i].Type = NucleusFile.FileType.Music;
                    }
                    else if (files[i].Attributes["type"].Value == "video")
                    {
                        retFiles[i].Type = NucleusFile.FileType.Video;
                    }
                    else if (files[i].Attributes["type"].Value == "package")
                    {
                        retFiles[i].Type = NucleusFile.FileType.Package;
                    }
                }
                return retFiles;
            }
            return null;
        }
    }
}
